#include "iSound.h"



iSound::iSound(LPWSTR fileName, SoundManager *manager) {
  this->fileName = fileName;
  this->soundManager = manager;
  this->buffer8 = NULL;
  this->threadHandle = NULL;
  this->fileHandle = NULL;
  //Init variable
  loop = false;
  playState = SOUND_STOP;
}


void iSound::WriteData(LPBYTE lpData, // pointer to input buffer
    DWORD dwOffSet, // offset of directsound buffer begin write
    DWORD dwSoundByte) { // size want to write
  LPVOID lpvPtr1; // pointer to part1
        DWORD dwBytes1; // part1 length
        LPVOID lpvPtr2; // pointer to part2
        DWORD dwBytes2; // part2 length
       
        //lock memory
        hResult = buffer8->Lock(dwOffSet, dwSoundByte, &lpvPtr1, &dwBytes1, &lpvPtr2, &dwBytes2, 0);

        // if error occur
        if(DSERR_BUFFERLOST == hResult) // data will lost in this case
        {
                buffer8->Restore();
                hResult = buffer8->Lock(dwOffSet, dwSoundByte, &lpvPtr1, &dwBytes1, &lpvPtr2, &dwBytes2, 0);
        }
        if(hResult == DS_OK) // lock successful
        {
                memcpy( lpvPtr1, lpData, dwBytes1);
                if(dwBytes2 >0) // write the second part
                        memcpy(lpvPtr2, lpData + dwBytes1, dwBytes2);
        } else {
		printf("Lock directsound buffer fail");
  }
        hResult = buffer8->Unlock(lpvPtr1,dwBytes1, lpvPtr2, dwBytes2);
        if(hResult != DS_OK)
        {
		printf("Unlock directsound buffer fail");
        }
}

void iSound::Play(bool loop) {}
void iSound::Pause() {}
void iSound::Stop() {}


iSound::iSound(void)
{

}


iSound::~iSound(void)
{
	if(this->fileHandle != NULL)
	{
		this->Stop();
		CloseHandle(this->fileHandle);
	}

}
